package com.atmilan.quartz.sync.push.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.UpdateFlagEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.BuyerProductDO;
import com.atmilan.quartz.model.entity.buyer.BuyerProductSkuMerged;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.model.entity.europe.EuropeBrand;
import com.atmilan.quartz.model.entity.europe.EuropeProductSku;
import com.atmilan.quartz.model.entity.europe.EuropeProductSkuMerged;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.IStoreCartService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerBrandService;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeBrandService;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeProductSkuMergedService;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeProductSkuService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrDO;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.sync.push.service.IProductListenerService;
import com.atmilan.quartz.utils.ImageSearchUtils;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.extern.slf4j.Slf4j;

/**
 * crmeb和luxury商品推送处理
 * @Description: 
 * @author daigb
 * @date 2021-01-25
 */
@Slf4j
@Service
public class ProductListenerServiceImpl implements IProductListenerService {
    public static final String CAT_MAP_STR = "21,1110;159,1110;165,1110;17,1111;18,1111;243,1111;16,1109;19,1109;20,1109;23,1109;175,1109;22,1112;160,1112;26,1097;27,1096;28,1095;29,1094;30,1098;117,1099;200,1100;33,1113;34,1130;35,1132;36,1114;40,1133;38,1168;39,1168;176,1168;44,1158;45,1190;46,1189;47,1189;49,1117;50,1116;51,1121;5,1080;6,1079;169,1091;241,1091;8,1081;12,1089;13,1083;14,1087;15,1093;161,1093;205,1093;124,1082;168,1090;187,1084;145,1084;146,1086;147,1085;148,1085;149,1086;150,1086;123,1087;139,1084;140,1084;141,1084;142,1084;143,1089;144,1084;193,1087;194,1093;242,1093;244,1104;245,1104;246,1104;73,1102;74,1107;76,1103;77,1106;78,1105;215,1108;216,1108;79,1044;80,1046;250,1045;251,1045;82,1043;84,1051;86,1052;94,1047;87,1113;89,1130;90,1132;91,1114;92,1168;93,1168;177,1168;111,1158;112,1190;113,1189;53,1073;54,1042;129,1034;130,1034;131,1034;132,1034;133,1034;198,1034;59,1038;60,1039;62,1040;127,1040;64,1033;154,1074;155,1031;163,1041;182,1040;184,1073;197,1034;55,1037;56,1037;158,1037;134,1036;135,1181;136,1035;137,1034;138,1034;151,1036;152,1034;217,1136;101,1134;102,1134;222,1134;223,1134;224,1134;225,1134;231,1134;232,1134;233,1134;234,1134;237,1134;239,1134;238,1134;97,1135;98,1135;103,1135;226,1135;227,1135;228,1135;229,1135;230,1135;235,1135;236,1135;240,1135";
    public static final String EUROPE_CAT_MAP_STR = "-40,1073;-47,1074;20000005,1031;-46,1033;-28,1034;-42,1034;-29,1036;-30,1037;-44,1037;-45,1038;20000007,1039;-35,1039;-43,1041;20000014,1042;20000019,1181;-51,1102;-60,1103;-57,1104;-58,1105;-53,1106;-54,1108;-21,1044;-19,1045;-1,1046;-17,1047;-22,1049;-43,1090;20000008,1092;-14,1113;-3,1114;-7,1130;29492952,1158;20000017,1168;-11,1189;20000023,1190;-8,1192;-4,1193;20000022,1116";
    public static final Integer DEFAULT_CAT_ID = 1859;
    public static final String EUROPE_BRAND_MAP_STR = "43,161;5897,912;1482,161;3573,161;3652,161;5362,161;5375,161;5699,161;5746,161;47,439;1291,439;1405,439;1762,439;2411,439;3015,439;3806,439;3857,439;3941,439;3988,439;10000007,439;19,442;4617,442;4193,442;2208,442;3845,442;4150,442;558,442;3,543;5781,543;3849,543;3850,543;3872,543;3920,543;3933,543;4077,543;4612,543;62,1064;63,1722;2534,1722;64,1066;448,337;65,337;66,850;73,207;2463,207;4850,207;5850,207;239,207;1297,207;1304,207;1735,207;1908,207;2808,207;2935,207;2961,207;3057,207;96,782;107,242;317,242;3848,242;3891,242;3919,242;4024,242;4141,242;4167,242;5243,242;114,438;1778,438;3318,886;5125,886;3844,603;3921,603;3934,603;4032,603;4412,603;5103,603;5814,603;5456,1025;1914,883;6117,883;4961,883;124,575;2354,575;4134,575;119,948;718,948;5053,522;4189,522;6208,2128;4742,2128;1355,50;1760,50;2546,50;2548,50;3803,50;3862,50;3864,50;3914,50;3997,50;4151,50;4644,50;5263,50;5874,50;3854,50;3855,50;131,512;1077,512;136,512;134,386;4118,386;134,386;4118,386;4138,386;3763,1036;3319,1036;5367,788;5704,788;4111,788;4169,788;679,655;5397,655;5412,655;5695,655;176,911;3293,911;4067,911;1940,627;2024,627;3815,627;5409,627;4436,344;6202,344;10000013,344;579,344;760,344;761,344;2556,344;3897,344;3904,344;4085,344;4114,344;594,344;3564,452;3907,452;4095,452;5059,452;5461,452;5872,452;170,452;191,452;1248,452;3336,452;3565,452;3923,451;3930,451;3913,451;236,451;531,451;5819,451;245,451;599,830;2462,830;4043,830;10000020,1906;5381,1906;241,402;4725,1788;4726,1788;4727,1788;3267,1874;5944,1874;1698,1874;2960,356;3843,356;4065,356;5710,356;5720,356;4018,336;3924,336;3952,336;3992,336;4149,336;4171,336;4128,336;5884,811;6179,811;6522,811;5822,837;5732,837;5745,837;5712,837;10000017,837;10000016,837;759,1791;409,1182;3966,517;5384,517;3976,517;1142,2147;4185,803;4187,803;4963,2023;4872,1777;6374,1068;6358,475;6122,475;1644,2105;161,1751;5727,1751;5888,1971;4948,1971;1411,826;5117,826;535,826;4905,2027;1809,2096;720,942;5402,1059;5422,1059;381,588;4831,588;4511,588;4052,588;4550,588;4001,299;4498,299;3881,299;3937,299;3999,299;3943,299;5836,833;3567,833;3566,833;3568,833;4088,99;4161,994881,99;379,99;3929,99;3989,99;4040,513;4046,513;4066,513;4004,513;4172,513;3868,202;3915,202;450,202;3964,202;3860,202;5363,211;4003,211;3995,211;4017,211;3958,211;442,211;5355,211;5452,211;4035,211;4002,211;5842,211;5772,211;1611,211;4069,377;3950,377;4181,377;1485,377;210,377;3863,571;3879,571;2221,571;4009,436;3916,436;4201,436;2615,436;315,436;512,436;4145,436;5229,436;2555,436;5700,436;427,436;1134,691;1607,691;5877,691;216,691;3955,691;4210,691;5325,691;3060,691;3659,433;2910,433;3572,433;3639,433;4832,433;2817,433;2816,433;5352,925;5321,925;2577,568;3578,568;2524,568;3620,568;2849,568;3128,1995;6585,1995;4934,1995;5783,1995;6523,1995;6471,1000;4224,957;166,1001;169,1001;4878,236;3874,236;3875,236;725,236;380,236;4006,236;277,868;4196,526;3593,146;3095,146;3091,146;3094,146;3557,146;3112,535;3576,535;3962,535;3536,535;2436,535;3088,535;3648,535;2494,535;3626,535;6163,535;2496,535;2196,535;5330,535;2492,535;2528,535;5264,535;3504,535;5269,535;4163,535;2593,462;5329,462;1474,462;287,462;1400,443;2231,443;5415,443;2876,1023;5716,1023;1269,165;306,165;4027,508;4212,508;5342,235;3795,235;3939,235;3893,235;4343,235;4400,235;2645,235;4421,235;4391,235;4394,235;3753,235;10000008,235;3667,235;1165,235;10000010,235;3712,235;3755,235;3552,235;4724,235;6459,235;3749,235;5344,235;4398,235;6377,235;4849,235;3666,235;5331,235;5521,235;4062,235;5343,235;10000009,235;280,235;6034,235;3901,160;6460,160;5462,735;4967,735;5338,735;1751,735;5988,735;3018,893;3076,893;3056,428;158,428;3290,1961;160,1950;1799,960;1294,2024;3647,1949721,1667;1254,1052;3451,2170;5406,1989;5949,1987;4836,978;4155,1015;5265,775;6041,958;295,392;3179,582;3078,458;5530,848;377,848;1592,848;2678,848;1401,523;3656,995;184,995;2355,721;1888,721;3702,721;3244,721;3101,721;6366,721;3531,721;1321,721;1822,721;4834,721;1632,721;3013,721;1627,721;3012,1781;5832,930;715,953;4076,953;5887,2188;3069,350;354,2083;3657,2083;3004,1804;716,834;649,742;5328,1793;3910,804;4375,804;5999,1725;3349,2081;5516,769;580,769;278,592;2059,2161;5686,2161;6053,836;4059,838;4110,838;5448,838;6385,701;3974,311;3851,311;3876,311;5408,311;2552,311;4666,311;3896,311;4096,311;3906,311;4097,311;1289,311;4174,311;3505,486;4505,486;5938,486;4045,488;3957,491;5454,862;723,685;4700,1062;10000018,206;5915,206;3809,206;5429,206;1175,206;3994,596;4090,596;4086,596;5137,596;6205,596;175,596;5828,4934;6339,515;4060,515;4075,515;4180,839;3948,839;10000015,839;5385,839;3814,839;5386,839;5396,839;3456,839;4844,593;5390,1988;4530,2116;2541,589;2530,589;4209,998;5751,1032;4063,747;4974,747;4192,747;180,1789;4010,781;4139,781;4019,781;3665,690;1153,496;5941,496;5464,1994;3155,1964;4103,614;5451,614;6272,1723;1271,904;744,986;5430,2038;319,1060;4092,122;3998,122;6353,122;1290,122;4221,122;3300,975;3699,975;3986,238;4177,500;4253,2036;1706,842;4658,809;4159,316;6065,316;4016,131;5416,946;3846,334;2430,1849;452,426;5337,959;4153,505;4904,505;1151,528;289,528;1044,528;3811,434;5769,1005;3497,1669;3192,2123;3298,2180;6369,2180;205,141;3191,1867;6515,1867;6392,1867;1268,2124;3971,2063;544,153;5991,642;5450,858;1154,2092;1835,2092;3237,2092;5498,1982;5033,780;5542,780;601,869;378,861;2921,1863;6276,1027;298,163;2644,536;3981,418;3886,418;4129,659;898,2016;322,1675;1387,599;4208,437;151,2017;3671,931;4025,514;6265,982;3284,880;389,1901;185,915;5084,760;6360,1683;382,764;3740,1730;3108,2019";
    public static final String NEW_EUROPE_BRAND_STR = "25,3313,3779,Kway;52,3847,3870,3972,5778,TOD'S;76,10000003,10000006,VALENTINO GARAVANI;85,5372,Atlantic Stars;737,108,401,6561,MM6;384,5839,5844,5848,1963,LIU JO;5099,5557,CAMPER;165,735,NUMERO;729,2927,TACCHINI;3634,3766,5366,GUESS;5876,4353,5417,Gcds;5368,3303,3611,3316,5364,5361,LIUJO;5438,4146,3125,1662,5906,4197,4041,4101,4222,4230,4020,453,3873,6474,MAISON;3800,3888,3993,3856,3980,3895,3925,10000004,10000005,VALENTINE;3770,3569,nenette;956,3546,OFFICINE CREATIVE;2617,2128,baO BAO;2937,5556,Braguette;214,1589,CRIME;3274,3533,DATE;5698,1602,2636,John;3746,4786,Katharine Hamnet London;413,5371,MANUEL RITZ;2544,1622,MARQUES ALMEIDA;5466,5483,MATERIEL;3285,3311,Replay;2097,2189,ROSSANO PERINI;658,3788,RRD;224,5849,3323,6274,SAUCONY;1080,4858,SEBAGO;5480,6345,SOLLECITI;2427,5332,WEEKEND";

    @Autowired
    PriceUtil priceUtil;
    @Autowired
    IEuropeProductSkuMergedService europeProductSkuMergedService;
    @Autowired
    IEuropeProductSkuService europeProductSkuService;
    @Autowired
    IBuyerBrandService buyerBrandService;
    @Autowired
    IEuropeBrandService europeBrandService;
    @Autowired
    private IStoreProductService storeProductService;
    @Autowired
    private IStoreCartService storeCartService;
    @Autowired
    private IStoreBrandService storeBrandService;
    @Value("${crmeb.domain}")
    private String crmebApiDomain;

    Map<Integer, Integer> catMap = new HashMap<>();
    Map<Integer, Integer> europeCatMap = new HashMap<>();
    Map<Integer, Integer> europeBrandCatMap = new HashMap<>();
    Map<String, String> europeNewBrandCatMap = new HashMap<>();

    List<String> buyerAllBrandIds = new ArrayList<>();
    List<String> buyerAllBrandNames = new ArrayList<>();

    @PostConstruct
    public void buildCatMap() {
        List<String> rowList = Arrays.asList(CAT_MAP_STR.split(";"));
        if (CollectionUtils.isNotEmpty(rowList)) {
            rowList.forEach(row -> {
                String[] cols = row.split(",");
                if (cols != null && cols.length == 2) {
                    catMap.put(Integer.valueOf(cols[0].trim()), Integer.valueOf(cols[1].trim()));
                }
            });
        }

        List<String> rowList2 = Arrays.asList(EUROPE_CAT_MAP_STR.split(";"));
        if (CollectionUtils.isNotEmpty(rowList2)) {
            rowList2.forEach(row -> {
                String[] cols = row.split(",");
                if (cols != null && cols.length == 2) {
                    europeCatMap.put(Integer.valueOf(cols[0].trim()), Integer.valueOf(cols[1].trim()));
                }
            });
        }

        List<String> rowList3 = Arrays.asList(EUROPE_BRAND_MAP_STR.split(";"));
        if (CollectionUtils.isNotEmpty(rowList3)) {
            rowList3.forEach(row -> {
                String[] cols = row.split(",");
                if (cols != null && cols.length == 2) {
                    europeBrandCatMap.put(Integer.valueOf(cols[0].trim()), Integer.valueOf(cols[1].trim()));
                }
            });
        }

        List<String> rowList4 = Arrays.asList(NEW_EUROPE_BRAND_STR.split(";"));
        if (CollectionUtils.isNotEmpty(rowList4)) {
            rowList4.forEach(row -> {
                String[] cols = row.split(",");
                for (int i = 0; i < cols.length; i++) {
                    if (i != cols.length - 1) {
                        europeNewBrandCatMap.put(cols[i], cols[cols.length - 1]);
                    } else {
                        europeNewBrandCatMap.put(cols[cols.length - 1], cols[0]);
                    }
                }
            });
        }
    }

    /**
     * 订阅商品推送消息
     */
    @Override
    public void receiveProductMsg(BuyerProductDO product) {
        // 下架这几种情况：更新标识为0、没有SKU数据、售价为null或0、ERP成本为0
        if (null != product.getIsEurope() && ProductTypeEnum.EUROPE.getCode() == product.getIsEurope()) {
            isEuropeProduct(product);
        } else {
            isBuyerProduct(product);
        }
    }

    private void isEuropeProduct(BuyerProductDO product) {
        if (product.getUpdateFlag() == UpdateFlagEnum.un_modify.getCode() 
                || CollectionUtils.isEmpty(product.getSkuList()) 
                || product.getSalePrice() == null || Double.parseDouble(product.getSalePrice()) <= 0) {
           // boolean ret = offlineEuropeProduct(product);
        } else {
            boolean ret = saveEuropeProduct(product);
            if (ret) {
                log.info("--------------- 保存europe商品返回结果id: {} ret: {} ---------------", product.getGoodsId(), ret);
            }
        }
    }

    private void isBuyerProduct(BuyerProductDO product) {
        if (product.getUpdateFlag() == UpdateFlagEnum.un_modify.getCode() 
                || CollectionUtils.isEmpty(product.getSkuList()) 
                || product.getSalePrice() == null || Double.parseDouble(product.getSalePrice()) <= 0) {
            // TODO 暂时不处理下架操作
//            String ret = offlineProduct(product);
//            if (StringUtils.isNotBlank(ret)) {
//                log.info("offline product return value : {} ret  =  {}", product.getGoodsId(), ret);
//            }
        } else {
            boolean ret = save(product);
            log.info("--------------- 保存buyer商品返回结果id: {} ret: {} ---------------", product.getGoodsId(), ret);
        }
    }

    private Boolean save(BuyerProductDO product) {
        boolean newProduct = true;

        StoreProductRequest productRequest = buildCrmebProduct(product);
        if (null == productRequest || CollectionUtils.isEmpty(productRequest.getAttrValue())) {
            return false;
        }

        //最后推送时间
        StoreProductCrmebRequest storeProductCrmebRequest = new StoreProductCrmebRequest();
        BeanUtils.copyProperties(productRequest, storeProductCrmebRequest);

        // 对象转换
        List<StoreProductAttr> storeProductAttr = JSON.parseArray(JSON.toJSONString(productRequest.getAttr()), StoreProductAttr.class);
        storeProductCrmebRequest.setAttr(storeProductAttr);

        storeProductCrmebRequest.setLastPushTime(new Date());
        if (storeProductCrmebRequest.getId() != null) {
            newProduct = false;
        } else if (StringUtils.isNotBlank(storeProductCrmebRequest.getBarCode())) {
            StoreProduct sp = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
            if (sp != null) {
                storeProductCrmebRequest.setId(sp.getId());
                //小编推荐
                storeProductCrmebRequest.setIsBest(sp.getIsBest());
                newProduct = false;
            }
        }

        if (newProduct) {
            storeProductService.save(storeProductCrmebRequest);
        } else {
            storeProductService.update(storeProductCrmebRequest);
        }

        return true;
    }

    private String offlineProduct(BuyerProductDO product) {
        String goodsId = product.getGoodsId();
        return offShell(goodsId);
    }

    private Boolean saveEuropeProduct(BuyerProductDO product) {
        try {
            if (product == null) {
                return null;
            }
            StoreProductRequest productRequest = buildCrmebEuropeProduct(product);
            if (productRequest == null) {
                return null;
            }
            return saveProduct(productRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private Boolean offlineEuropeProduct(BuyerProductDO product) {
        return offlineEuropeProductDistribute(product, crmebApiDomain);
    }

    private StoreProductRequest buildCrmebProduct(BuyerProductDO product) {
        // 这里从 sku_merged 表里取，已经去重并且合并了库存
        List<BuyerProductSkuMerged> list = product.getSkuList();
        // sku 如果没有同步到的updateflag=0 也推过去, 把库存清零
        // 没有有效sku的商品不同步
        if (CollectionUtils.isEmpty(list)) {
            log.warn("drop product: {} , no sku val", product.getGoodsId());
            return null;
        }

        List<StoreProductAttrDO> attrList = new ArrayList<StoreProductAttrDO>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

        StoreProductAttrDO storeProductAttr = new StoreProductAttrDO();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);

        StoreProductAttrDO storeProductAttrColor = new StoreProductAttrDO();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);

        BigDecimal price = null == product.getSalePrice() ? BigDecimal.ZERO : new BigDecimal(product.getSalePrice());
        BigDecimal promotePrice = null == product.getPromotePrice() ? BigDecimal.ZERO : new BigDecimal(product.getPromotePrice());
        BigDecimal originalPrice = null == product.getOriginalPrice() ? BigDecimal.ZERO : new BigDecimal(product.getOriginalPrice());
        BigDecimal erpPrice = null == product.getErpPrice() ? BigDecimal.ZERO : new BigDecimal(product.getErpPrice());
        BigDecimal sourceCost = null == product.getSourceCost() ? BigDecimal.ZERO : new BigDecimal(product.getSourceCost());
        String goodsImg = product.getGoodsImg();
        list.forEach(buyerProductSku -> {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            //活动价
            storeProductAttrValueRequest.setPromotePrice(promotePrice);
            //售价
            storeProductAttrValueRequest.setPrice(price);
            // 原价
            storeProductAttrValueRequest.setOtPrice(originalPrice);
            // 成本价 , 如果有 erp_prom_price 就用 erp_prom_price
            storeProductAttrValueRequest.setCost(erpPrice);
            //原成本价
            storeProductAttrValueRequest.setSourceCost(sourceCost);
            storeProductAttrValueRequest.setImage(goodsImg);
            // 如果sku上次同步未拿到最新的数据，就把库存设置成0，当成下架处理
            storeProductAttrValueRequest.setStock(buyerProductSku.getUpdateFlag() == UpdateFlagEnum.un_modify.getCode() ? 0 : buyerProductSku.getStock());

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<String, String>();
            List<String> suk = new ArrayList<String>();
            String color = buyerProductSku.getColor();
            if (StringUtils.isNotBlank(color)) {
                linkedMap.put("颜色", color);
                storeProductAttrColor.addValue(color);
                suk.add(color);
            }
            String size = buyerProductSku.getSize();
            if (StringUtils.isNotBlank(size)) {
                linkedMap.put("尺寸", size);
                storeProductAttr.addValue(size);
                suk.add(size);
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValueRequest);
        });
        if (CollectionUtils.isNotEmpty(storeProductAttrColor.getValueList())) {
            storeProductAttrColor.setAttrValues(String.join(",", storeProductAttrColor.getValueList()));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(storeProductAttr.getValueList())) {
            storeProductAttr.setAttrValues(String.join(",", storeProductAttr.getValueList()));
            attrList.add(storeProductAttr);
        }
        // 抽取所有size属性去重
        StoreProductRequest productRequest = new StoreProductRequest();
//        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        // 强制写一个 商户id 作为buyer商品标识标识
        productRequest.setMerId(CrmebMerchantEnums.BUYER.getMerchantId());
        productRequest.setContent(product.getGoodsName());
        productRequest.setKeyword(product.getGoodsCode());
        productRequest.setStoreInfo(product.getGoodsCaizhi());
        productRequest.setStoreName(product.getGoodsName());
        productRequest.setBrandId(Integer.valueOf(product.getBrandId()));
        productRequest.setBrandName(product.getBrandName());
        productRequest.setPostage(new BigDecimal(product.getShippingFee()));
        //售价
        productRequest.setPrice(price);
        //活动价
        productRequest.setPromotePrice(promotePrice);
        // 原价
        productRequest.setOtPrice(originalPrice);
        // 成本价
        productRequest.setCost(erpPrice);
        //原成本价
        productRequest.setSourceCost(sourceCost);

        //活动价标记
        productRequest.setPromoteFlag(product.getPromoteFlag());
        productRequest.setErpPromFlag(product.getErpPromFlag());

        //供应商
        productRequest.setSuppliersId(product.getSuppliersId());
        productRequest.setSuppliersName(product.getSuppliersName());

        // 没有映射的类目，放到其他区
        Integer newCatId = catMap.containsKey(product.getCatId()) ? catMap.get(product.getCatId()) : DEFAULT_CAT_ID;
        productRequest.setCateId(newCatId);
        productRequest.setCateIds(new ArrayList<Integer>(newCatId));
        productRequest.setImage(goodsImg);
        productRequest.setBarCode(BarCodeEnum.BUYER.getCode() + product.getGoodsId());
        if (StringUtils.isNotEmpty(product.getGallery())) {
            JSONArray arr = (JSONArray) JSONArray.parse(product.getGallery());
            List<String> sliderImages = new ArrayList<String>();
            if (arr != null && arr.size() > 0) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSort(0);
        productRequest.setSpecType(true);
        productRequest.setIsEurope(ProductTypeEnum.BUYER.getCode());
        productRequest.setTempId(product.getStockArea());
        productRequest.setUnitName("件");
        if (null != product.getSuppliersId() && StringUtils.equals(product.getSuppliersId()+"", String.valueOf(2))) {
            productRequest.setMerUse(true);
        }
        return productRequest;
    }

    private String offShell(String barCode) {
        StoreProduct storeProduct = storeProductService.getByBarCode(barCode, null, null);
        if (storeProduct == null) {
            log.warn("买手端消费数据 - 下架商品 - not exists! barCode: {}", barCode);
            return null;
        }
        storeProduct.setIsShow(false);
        if (storeProductService.updateById(storeProduct)) {
            storeCartService.productStatusNotEnable(storeProduct.getId());
            log.warn("买手端消费数据 - 下架商品 - 成功, barCode:{} ", barCode);
            return barCode;
        } else {
            return null;
        }
    }

    public StoreProductRequest buildCrmebEuropeProduct(BuyerProductDO by) {
        // 这里从 sku_merged 表里取，已经去重并且合并了库存
        List<EuropeProductSkuMerged> list = europeProductSkuMergedService.getByGoodsId(by.getGoodsId() + "");
        // sku 如果没有同步到的updateflag=0 也推过去, 把库存清零
        // 没有有效sku的商品不同步
        if (CollectionUtils.isEmpty(list)) {
            log.warn("drop product: {} , no sku val", by.getGoodsId());
            return null;
        }

        List<StoreProductAttrDO> attrList = new ArrayList<StoreProductAttrDO>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

        StoreProductAttrDO storeProductAttr = new StoreProductAttrDO();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);

        StoreProductAttrDO storeProductAttrColor = new StoreProductAttrDO();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);

        // 售价 , 在Europe的基础上上浮浮 1.05%
        BigDecimal price = by.getPrice();//欧元
        /*//将欧元转换成港币
        BigDecimal costPrice = priceUtil.eur2hk(price);//成本价-港币*/
        //将欧元转换成人民币
        BigDecimal costRmbPrice = price;//成本价-人民币
        //售价，成本价的基础上*1.2(向上取整)
        //        BigDecimal salePrice = new BigDecimal(costRmbPrice.multiply(new BigDecimal(1.2)).setScale(2, BigDecimal.ROUND_UP).longValue());
        BigDecimal salePrice = costRmbPrice;
        BigDecimal referencePrice = by.getReferencePrice();//原价（欧元不转换成人民币）
        list.forEach(skuMerged -> {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setImage(by.getGoodsImg());
            // 售价
            storeProductAttrValueRequest.setPrice(salePrice);
            // 原价
            storeProductAttrValueRequest.setOtPrice(referencePrice);
            // 成本价 , 如果有 erp_prom_price 就用 erp_prom_price
            storeProductAttrValueRequest.setCost(costRmbPrice);
            // 如果sku上次同步未拿到最新的数据，就把库存设置成0，当成下架处理
            storeProductAttrValueRequest.setStock(skuMerged.getUpdateFlag() == UpdateFlagEnum.un_modify.getCode() ? 0 : skuMerged.getStock());

            LinkedHashMap linkedMap = new LinkedHashMap();
            List<String> suk = new ArrayList<String>();
            if (StringUtils.isNotBlank(skuMerged.getColor())) {
                linkedMap.put("颜色", skuMerged.getColor());
                storeProductAttrColor.addValue(skuMerged.getColor());
                suk.add(skuMerged.getColor());
            }
            if (StringUtils.isNotBlank(skuMerged.getSize())) {
                linkedMap.put("尺寸", skuMerged.getSize());
                storeProductAttr.addValue(skuMerged.getSize());
                suk.add(skuMerged.getSize());
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValueRequest);
        });
        if (CollectionUtils.isNotEmpty(storeProductAttrColor.getValueList())) {
            storeProductAttrColor.setAttrValues(String.join(",", storeProductAttrColor.getValueList()));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(storeProductAttr.getValueList())) {
            storeProductAttr.setAttrValues(String.join(",", storeProductAttr.getValueList()));
            attrList.add(storeProductAttr);
        }
        // 抽取所有size属性去重
        StoreProductRequest productRequest = new StoreProductRequest();
//        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        // 强制写一个 商户id 作为buyer商品标识标识
        productRequest.setMerId(CrmebMerchantEnums.BUYER.getMerchantId());
        productRequest.setContent(by.getGoodsName());
        productRequest.setKeyword(by.getCode());
        List<EuropeProductSku> europeProductSku = europeProductSkuService.getEuropeProductSkuListByGoodsId(by.getGoodsId() + "");
        productRequest.setStoreInfo(null == europeProductSku || 0 == europeProductSku.size() ? "" : europeProductSku.get(0).getComposition());//商品材质
        productRequest.setStoreName(by.getGoodsName());
        //品牌进行处理
        //首先与buyer进行对比，是否全匹配，如果全匹配，则保存buyer品牌brand_id
        Integer europeBrandId = null == by.getBrandId() ? 0 : Integer.parseInt(by.getBrandId());
        EuropeBrand europeBrand = europeBrandService.getById(europeBrandId);
        //如果欧洲品牌表中查不到此品牌，则匹配到其他品牌中
        if (europeBrand == null) {//为空，匹配到其他类目
            productRequest.setBrandId(88888888);
            productRequest.setBrandName("OTHER");
        } else {
            List<String> allBrandName = buyerBrandService.getAllBrandName();
            for (String brandName : allBrandName) {
                if (brandName.equalsIgnoreCase(europeBrand.getBrandName())) {
                    productRequest.setBrandId(buyerBrandService.getBrandIdByBrandName(brandName).getBrandId());
                    productRequest.setBrandName(brandName);
                    break;
                }
            }
            if (productRequest.getBrandId() == null || productRequest.getBrandId() == 0) {
                if (europeBrandCatMap.containsKey(europeBrandId)) {//此品牌id已在buyer中存在，一一对应
                    productRequest.setBrandId(europeBrandCatMap.get(europeBrandId));
                } else if (europeNewBrandCatMap.containsKey(europeBrandId)) {//此品牌在buyer中不存在，但多个Europe品牌对应一个Europe品牌
                    String newBrandName = europeNewBrandCatMap.get(europeBrandId);
                    String oldBrandId = europeNewBrandCatMap.get(newBrandName);
                    if (oldBrandId.length() >= 6) {
                        productRequest.setBrandId(Integer.parseInt(oldBrandId));//品牌数据需要保存到Crmeb端
                        productRequest.setBrandName(newBrandName);
                    } else {
                        productRequest.setBrandId(Integer.parseInt("9999" + oldBrandId));//品牌数据需要保存到Crmeb端
                        productRequest.setBrandName(newBrandName);
                    }
                } else {//此品牌在buyer中不存在，一个europe品牌对应一个europe品牌
                    String oldBrandId = by.getBrandId() + "";
                    if (oldBrandId.length() >= 6) {
                        productRequest.setBrandId(Integer.parseInt(by.getBrandId()));
                        productRequest.setBrandName(europeBrand.getBrandName());
                        //oldBrandId = oldBrandId.substring(0,5);
                    } else {
                        productRequest.setBrandId(Integer.parseInt("9999" + oldBrandId));
                        productRequest.setBrandName(europeBrand.getBrandName());
                    }
                }
            }
        }
        //buyer会自动计算运费
        //商品价格（售价）
        productRequest.setPrice(salePrice);
        // 原价
        productRequest.setOtPrice(referencePrice);
        // 成本价
        productRequest.setCost(costRmbPrice);
        // 没有映射的类目，放到其他区
        Integer newCatId = europeCatMap.containsKey(by.getCategoryId()) ? europeCatMap.get(by.getCategoryId()) : DEFAULT_CAT_ID;
        productRequest.setCateId(newCatId);
        productRequest.setCateIds(new ArrayList(newCatId));
        productRequest.setImage(by.getGoodsImg());
        productRequest.setBarCode(BarCodeEnum.EUROPE.getCode() + by.getGoodsId());
        if (StringUtils.isNotEmpty(by.getGallery())) {
            JSONArray arr = (JSONArray) JSONArray.parse(by.getGallery());
            List<String> sliderImages = new ArrayList<String>();
            if (arr != null && arr.size() > 0) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSort(0);
        productRequest.setSpecType(true);
        //        productRequest.setFicti(RandomUtil.randomInt(50));
        // 映射stockarea 1，2 3
        productRequest.setTempId(3);//发货地欧洲
        productRequest.setUnitName("件");
        //
        if (StringUtils.isNotBlank(by.getSupplierId() + "") && StringUtils.equals(by.getSupplierId() + "", String.valueOf(2))) {
            productRequest.setMerUse(true);
        }
        //设置第三方成本价
        productRequest.setSourceCost(by.getPrice());
        //是否是europe接口数据
        productRequest.setIsEurope(1);
        //设置供应商名称
        productRequest.setSuppliersId(99999999);
        productRequest.setSuppliersName("1MAG");
        return productRequest;
    }

    private boolean saveProduct(StoreProductRequest storeProductRequest) {
        try {
            //判断是否需要新增品牌
            Integer brandId = storeProductRequest.getBrandId();
            List<StoreBrand> list = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getId, brandId));
            if (list != null && list.size() > 0) {//品牌存在
                //StoreBrand storeBrand = storeBrandService.getByBrandId(brandId);
                //if(storeBrand != null ){//此品牌已存在
            } else {//此品牌不存在，新增
                StoreBrand storeBrand1 = new StoreBrand();
                storeBrand1.setId(brandId);
                storeBrand1.setCreateTime(cn.hutool.core.date.DateUtil.date());
                storeBrand1.setEnName(storeProductRequest.getBrandName());
                String fristHead = storeProductRequest.getBrandName().substring(0, 1);
                if (fristHead.matches("[a-zA-Z]")) {//首字母不为其他字符
                    storeBrand1.setLetter(fristHead.toUpperCase());
                } else {
                    storeBrand1.setLetter("#");
                }
                storeBrandService.save(storeBrand1);
            }
            boolean newProduct = true;
            boolean resultFlag = false;
            //最后推送时间
            storeProductRequest.setLastPushTime(new Date());
            if (storeProductRequest.getId() != null) {
                newProduct = false;
                // update
            } else if (StringUtils.isNotBlank(storeProductRequest.getBarCode())) {
                StoreProduct sp = storeProductService.getByBarCode(storeProductRequest.getBarCode(), storeProductRequest.getSuppliersId(), storeProductRequest.getKeyword());
                if (sp != null) {
                    storeProductRequest.setId(sp.getId());
                    storeProductRequest.setIsBest(sp.getIsBest());
                    newProduct = false;
                }
            }
            StoreProductCrmebRequest storeProductCrmebRequest = new StoreProductCrmebRequest();
            BeanUtils.copyProperties(storeProductRequest, storeProductCrmebRequest);

            // 对象转换
            List<StoreProductAttr> storeProductAttr = JSON.parseArray(JSON.toJSONString(storeProductRequest.getAttr()), StoreProductAttr.class);
            List<StoreProductAttrValueRequest> storeProductAttrValue = JSON.parseArray(JSON.toJSONString(storeProductRequest.getAttrValue()), StoreProductAttrValueRequest.class);
            storeProductCrmebRequest.setAttr(storeProductAttr);
            storeProductCrmebRequest.setAttrValue(storeProductAttrValue);
            if (newProduct) {
                resultFlag = storeProductService.save(storeProductCrmebRequest);
            } else {
                resultFlag = storeProductService.update(storeProductCrmebRequest);
            }
            if (resultFlag) {
                return resultFlag;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private Boolean offlineEuropeProductDistribute(BuyerProductDO product, String apiDomain) {
        try {
            if (product == null) {
                return null;
            }
            String goodsId = product.getGoodsId();
            String barCode = "/eu-" + goodsId;

            StoreProduct storeProduct = storeProductService.getByBarCode(barCode, null, null);
            if (storeProduct == null) {
                log.warn("not exists! barCode: {}", barCode);
                return true;
            }
            storeProduct.setIsShow(false);
            if (storeProductService.updateById(storeProduct)) {
                storeCartService.productStatusNotEnable(storeProduct.getId());
                //删除图片
                Integer id = storeProduct.getId();
                if (null != id) {
                    //图像搜索-删除图片
                    ImageSearchUtils.deleteImage(id.toString(), storeProduct.getKeyword());

                    //阿里云 -删除图片
                    //OSSUtil.deleteFile(storeProduct.getImage());

                    //视觉搜索-数据库里删除商品图片
                    //VisionSearchUtil.deleteImage(id.toString());
                }
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            log.error("getOfflineUrl Api Fail" + e);
        }

        return false;
    }

}
